/**
 * Created by zhouli on 18/3/8
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {Button, Form, Select, Input, Col, Row, message, Tooltip, DatePicker, Icon, TimePicker} from 'antd';
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
import moment from 'moment';
import {connect} from 'react-redux';
import Chooser from 'components/chooser';
import menuRoute from 'routes/menuRoute';
import {messages, deepCopy} from 'share/common';
import {
  personObjDefaultWithoutExtend,
} from 'containers/enterprise-manage/person-manage/person-detail/person-detail.model';
import 'styles/enterprise-manage/person-manage/person-detail/person-detail-components/basic-info.scss';
import {ImageUpload} from 'components/index';
import BIService from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/basic-info.service';
import PositionInfo from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/position-info';

const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;

class PersonBasicInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      deletedPositions: [],//删除的岗位信息
      userJobsDTOs: [],//岗位信息
      personObj: {
        customFormValues: []
      },
      data: [],
      genderData: [],
      preFixList: [],
    }
  }

  componentWillMount() {
    this.setState({personObj: this.props.basicInfoData});
  }

  componentDidMount() {
    //手机号前缀
    this.getMobilevalidateList();
    //性别
    this.getSystemValueList(1007)
      .then(res => {
      this.setState({
        genderData: res.data.values
      })
    });
  }

  componentWillReceiveProps(nextProps) {
    let personObj = nextProps.basicInfoData;
    personObj.userJobsDTOs.map((item, index)=>{
      //加一个序号，编辑的时候不能修改顺序
      item._index = index;
    })
    this.setState({
      personObj,
      userJobsDTOs: personObj.userJobsDTOs
    }, () => {
      setTimeout(() => {
        //刷新子组件
        this.childPostionInfo && this.childPostionInfo.refreshPositionInfo(personObj.userJobsDTOs)
      })
    });
  }

  getMobilevalidateList = () => {
    PDService.getMobilevalidateList()
      .then((res) => {
        this.setState({
          preFixList: res.data
        });
      })
  };
  // 把表单的值设置到人员信息扩展字段里面去
  /*
  * 注意，这里扩展字段有两种类型，一种是常规类型，配置的扩展字段就是显示
  * 一种是特殊配置的，比如用车必填字段，需要传code，需要同步到下游数据
  * 这个参数在第一次新增的会保存code，之后编辑就直接保存值，但是针对特殊配置，编辑也需要传code
  * */
  setFromToCustomFormValues = (values) => {
    let {personObj} = this.state;
    let customFormValues = personObj.customFormValues;
    if (customFormValues) {
      for (let key in values) {
        for (let i = 0; i < customFormValues.length; i++) {
          if (customFormValues[i].fieldOID === key) {
            if (customFormValues[i].messageKey === "common.date") {
              customFormValues[i].value = values[key] ? new Date(moment(values[key]).format("YYYY-MM-DD")) : "";
            } else if (customFormValues[i].messageKey === "time") {
              if (values[key]) {
                customFormValues[i].value = moment(values[key]).format("HH:mm");
              } else {
                customFormValues[i].value = "";
              }
            } else if (customFormValues[i].messageKey === "image") {
              //把attachmentImages赋值，只是为了前端展示
              customFormValues[i].attachmentImages = values[key];
              //这个地方要注意一下 服务端返回的图片字段是attachmentImages
              //但是上传的时候是attachments
              customFormValues[i].attachments = values[key];
              //还需要把value设置一下
              if (customFormValues[i].attachments) {
                let _values = [];
                for (let j = 0; j < customFormValues[i].attachments.length; j++) {
                  _values.push(customFormValues[i].attachments[j].attachmentOID);
                }
                customFormValues[i].value = JSON.stringify(_values);
              }
            } else {
              if(customFormValues[i].messageKey === "cust_list"){
                /*
                * 特殊控制
                * 先把 values[key] 当成 messageKey，找 value
                * */
                let val = this._findValue(values[key], customFormValues[i].customEnumerationList.values);
                if(val){
                  customFormValues[i].value = val
                }else {
                  // 如果找不到
                  customFormValues[i].value = values[key]
                }
              }else {
                customFormValues[i].value = values[key]
              }
            }
          }
        }
      }
    }
  };
  _findValue = (val, list) => {
    let res = null;
    list.map(item=>{
      if(val===item['messageKey']){
        res = item.value
      }
    });
    return res;
  };
  //挂载子组件
  onMountPostionInfo = (postionInfo) => {
    this.childPostionInfo = postionInfo;
  };
  //检查剩下的岗位信息中，是否包含被删除的岗位所在公司，如果有，需要把剩下的第一个公司，设置为主岗
  checkDeleteHasJobs = (deletedRecord, userJobsDTOs) => {
    if (deletedRecord.companyMainPosition) {
      let len = userJobsDTOs.length;
      deletedRecord.uni_id = deletedRecord.companyId + deletedRecord.departmentId + deletedRecord.position;
      for (let i = 0; i < len; i++) {
        let item = userJobsDTOs[i];
        item.uni_id = item.companyId + item.departmentId + item.position;
        if (item.uni_id !== deletedRecord.uni_id && deletedRecord.companyId === item.companyId) {
          //不设置被删除的岗位的公司，设置与被删除岗位包含一样的公司
          item.companyMainPosition = true;
          return userJobsDTOs;//只设置第一个
        }
      }
    }
    return userJobsDTOs
  };
  userJobsDTOChange = (_userJobsDTOs, deletedRecord) => {
    let {deletedPositions, personObj} = this.state;
    let userJobsDTOs = _userJobsDTOs;
    if (deletedRecord) {
      userJobsDTOs = this.checkDeleteHasJobs(deletedRecord, _userJobsDTOs);
    }
    userJobsDTOs.map((item, index) => {
      item.uni_id = item.companyId + item.departmentId + item.position;
      if (item.deleted) {
        item.id && deletedPositions.push(item);
        userJobsDTOs.splice(index, 1)
      }
    });
    personObj.userJobsDTOs = this.uniqueJobs(userJobsDTOs);
    this.setState({
      personObj,
      userJobsDTOs: this.uniqueJobs(userJobsDTOs),
      deletedPositions: this.uniqueJobs(deletedPositions),
    }, () => {
      //刷新子组件
      this.childPostionInfo.refreshPositionInfo(userJobsDTOs)
    })
  };
  //去重
  uniqueJobs = (jobs) => {
    let arr = [];
    let obj = {};
    for (let i = 0; i < jobs.length; i++) {
      let userJobsDTO = jobs[i];
      let uni_id = userJobsDTO.companyId + userJobsDTO.departmentId + userJobsDTO.position;
      if (!obj[uni_id]) {
        obj[uni_id] = true;
        arr.push(userJobsDTO)
      }
    }
    return arr;
  };
  //点击保存
  handleSave = (e) => {
    e.preventDefault();
    let {personObj, userJobsDTOs, deletedPositions} = this.state;
    let requestPersonObj = {};//请求对象
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setFromToCustomFormValues(values);
        if (values.gender + "" === "0" || values.gender === "男") {
          values.gender = 0;
        } else if (values.gender + "" === "1" || values.gender === "女") {
          values.gender = 1;
        } else {
          //2代表未知
          values.gender = 2;
        }
        let originPersonObj = deepCopy(personObj);
        if (personObj.userOID) {
          this.setState({
            loading: true,
          });
          /*
          * 扩展字段，岗位信息，单独特殊处理
          * */
          requestPersonObj = BIService.getUpdatePersonObj(personObj, values);
          Object.assign(requestPersonObj,{
            customFormValues: originPersonObj.customFormValues,//
            userJobsDTOs: userJobsDTOs.concat(deletedPositions),
          });
          requestPersonObj.userJobsDTOs.map(item => item.userId = originPersonObj.userId);
          /*
          * 这个接口报错信息注意,后端不会指定字段
          * 邮箱格式传的不对：email，报错说 传的不是json
          * 性别字段传的不对：gender，报错说 传的不是json
          * */
          PDService.updatePersonDetail(requestPersonObj)
            .then((res) => {
              message.success(messages("common.operate.success"));
              this.setState({
                loading: false,
                deletedPositions: []
              });
              this.props.savedData(res.data);
            })
            .catch(() => {
              this.setState({
                loading: false,
              });
            })
        } else {
          requestPersonObj = BIService.getCreatePersonObj(personObj, personObjDefaultWithoutExtend, values);
          requestPersonObj.customFormValues = originPersonObj.customFormValues;
          if (userJobsDTOs && userJobsDTOs.length) {
            //如果是新增岗位，且是删除状态，上传也没影响，后端不处理
            requestPersonObj.userJobsDTOs = userJobsDTOs.concat(deletedPositions);
            //校验一下是否有主岗位
            if (!BIService.checkCompanyMainPosition(deepCopy(userJobsDTOs))) {
              message.warn(messages('enterprise-manage.key382')/*请至少设置一个主岗位*/);
              return
            }
          } else {
            message.warn(messages('enterprise-manage.key383')/*请输入岗位信息*/);
            return
          }
          this.setState({
            loading: true,
          });
          PDService.createPersonDetail(requestPersonObj)
            .then((res) => {
              message.success(messages("common.operate.success"));
              this.setState({
                loading: false,
                deletedPositions: []
              });
              this.props.savedData(res.data);
              let record = res.data;
              let path = menuRoute.getRouteItem('person-detail', 'key').url.replace(":userOID", record.userOID);
              this.context.router.push(path);
            })
            .catch(() => {
              this.setState({
                loading: false,
              });
            })
        }
      }
    });
  };

  handleChange = (val) => {
    if (this.state.loading) {
      this.setState({
        loading: false
      })
    }
  };

  //点击取消
  handleCancel = (e) => {
    e.preventDefault();
    this.props.form.resetFields();
    this.props.toNoEditing();
    this.props.savedData(this.state.personObj);
  };

  //渲染非编辑状态
  renderNoEditing = () => {
    let {personObj, userJobsDTOs} = this.state;
    let items = BIService.getShowItems(personObj);
    return (
      <div className="info-item-wrap">
        {items.map((item, index) => {
          return (<div className="info-item f-left" key={index}>
            <div className="info-item-title">
              {item.label}
            </div>
            <div className="info-item-text">
              {item.name}
            </div>
          </div>)
        })}
        <div className="clear"/>
        <div>
          {userJobsDTOs.length > 0 && <PositionInfo
            isEdit={false}
            onRef={this.onMountPostionInfo}
            userJobsDTOs={userJobsDTOs}/>}
        </div>
        <div className="clear"/>
        <div>
          {this.renderExtendTitle()}
        </div>
        {this.renderNoEditingForExtend()}
      </div>
    )
  };

  //渲染非编辑状态
  renderNoEditingForExtend = () => {
    let {personObj} = this.state;
    let values = personObj.customFormValues ? personObj.customFormValues : [];
    let dom = [];
    for (let i = 0; i < values.length; i++) {
      if(values[i].fieldName.indexOf(messages('enterprise-manage.key496'/*公务卡状态*/)) === -1) {//扩展字段去掉公务卡状态
        dom.push(BIService.renderContentByMessageKey(values[i]))
      }
    }
    return (
      <div>
        {dom}
        <div className="clear"/>
      </div>
    )
  };

  // -----扩展字段 编辑状态---start
  renderEditingField = (values) => {
    let dom = [];
    for (let i = 0; i < values.length; i++) {
      if(values[i].fieldName.indexOf(messages('enterprise-manage.key496'/*公务卡状态*/)) === -1){//扩展字段去掉公务卡状态
        dom.push(this.renderEditingContentByMessageKey(values[i]))
      }
    }
    return dom;
  };
  renderEditingContentByMessageKey = (field) => {
    let messageKey = field.messageKey;
    //分为：单行输入框，多行输入框，值列表，日期，数字，时间，图片
    switch (messageKey) {
      case "input": {
        return this.renderEditingFiled_input(field);
        break;
      }
      //话费额度
      case "MonthLimited": {
        return this.renderEditingFiled_input(field);
        break;
      }
      //用车制度
      case "regulation_input": {
        return this.renderEditingFiled_input(field);
        break;
      }
      case "text_area": {
        return this.renderEditingFiled_text_area(field);
        break;
      }
      case "cust_list": {
        return this.renderEditingFiled_cust_list(field);
        break;
      }
      case "date": {
        return this.renderEditingFiled_date(field);
        break;
      }
      case "common.date": {
        return this.renderEditingFiled_date(field);
        break;
      }
      case "number": {
        return this.renderEditingFiled_number(field);
        break;
      }
      case "time": {
        return this.renderEditingFiled_time(field);
        break;
      }
      case "image": {
        return this.renderEditingFiled_image(field);
        break;
      }
    }
  };
  renderEditingFiled_input = (field) => {
    const {getFieldDecorator} = this.props.form;
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              max: 50,
              message: messages('enterprise-manage.key155'/*最多输入50个字符*/)
            },
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <Input placeholder={messages('common.please.enter')}/>)}
      </FormItem>
    )
  };
  renderEditingFiled_text_area = (field) => {
    const {getFieldDecorator} = this.props.form;
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              max: 200,
              message: messages('enterprise-manage.key156'/*最多输入200个字符*/)
            },
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <TextArea placeholder={messages('common.please.enter')}/>)
        }
      </FormItem>
    )
  };
  renderEditingFiled_cust_list = (field) => {
    const {getFieldDecorator} = this.props.form;
    //如果是值列表类型，在返回的数据上，前端多挂了一个 customEnumerationList 属性，
    //这个选择列表就从这个属性上拿了
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <Select>
            {field.customEnumerationList && _renderCustomEnumerationList(field.customEnumerationList.values)}
          </Select>
        )}
      </FormItem>
    )

    //渲染值列表
    function _renderCustomEnumerationList(list) {
      let dom = [];
      if (list.length > 0) {
        list.map(function (item) {
          /*
          * 要做多语言，这个地方上传 code，后端返回的时候，任然是 messageKey，所以显示的时候用 messageKey 去查 value 显示
          * code 值是 null，所以传 value，值列表的 value 就是 code
          * 之前上传的是 messageKey
          * dom.push(<Option key={item.id} value={item.messageKey}>{item.messageKey}</Option>)
          * */
          dom.push(<Option key={item.id} value={item.value}>{item.messageKey}</Option>)
        })
        return dom;
      } else {
        return ("");
      }
    }
  };
  renderEditingFiled_date = (field) => {
    const {getFieldDecorator} = this.props.form;
    let val = field.value ? moment(field.value).format("YYYY-MM-DD") : new Date();
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: moment(val, 'YYYY-MM-DD'),
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <DatePicker format={'YYYY-MM-DD'}/>
        )
        }
      </FormItem>
    )
  };
  renderEditingFiled_number = (field) => {
    const {getFieldDecorator} = this.props.form;
    field.unit = null;
    if (field.fieldContent) {
      let content = {};
      try {
        content = JSON.parse(field.fieldContent);
      }
      catch (e) {
      }
      field.unit = content.unit;
      if (field.unit && field.unit.length > 0) {
        field.unit = "(" + field.unit + ")";
      } else {
        field.unit = "";
      }
    }
    // 要根据限制条件进行校验
    let fieldConstraint = {
      integerMaxLength: "",
      decimalMaxLength: "",
    }
    if (field.fieldConstraint) {
      let _fieldConstraint = JSON.parse(field.fieldConstraint);
      fieldConstraint.integerMaxLength = _fieldConstraint.integerMaxLength;
      fieldConstraint.decimalMaxLength = _fieldConstraint.decimalMaxLength;
      field._fieldConstraint = fieldConstraint;
    }

    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName + field.unit}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: field.value,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            },
            {
              message: messages('enterprise-manage.key157'/*整数位数最多*/) + fieldConstraint.integerMaxLength + "," +
              messages('enterprise-manage.key158'/*小数位最多*/) + fieldConstraint.decimalMaxLength,
              validator: (fieldConstraint, value, cb) => {
                //必须是必填的才有校验
                if (field.fieldConstraint && field.required && value) {
                  let fieldConstraint = field._fieldConstraint;
                  if ((value.split(".")[0].length > fieldConstraint.integerMaxLength) ||
                    (value.split(".")[1] && value.split(".")[1].length > fieldConstraint.decimalMaxLength)) {
                    cb(false);
                    return;
                  } else {
                    cb();
                  }
                } else {
                  cb();
                }
              },
            }
          ]
        })(
          <Input type="number" placeholder={messages('common.please.enter')}/>)
        }
      </FormItem>
    )
  };
  onChangeTime = (time) => {
  };
  renderEditingFiled_time = (field) => {
    const {getFieldDecorator} = this.props.form;
    //这个  field.value 就直接显示，正式环境没有这种数据
    //其他环境不管
    let val = moment(field.value, 'HH:mm');
    if (field.value === null || field.value === "") {
      val = "";
    }
    if (field.value && field.value.length > 5) {
      //兼容以前的
      val = moment(field.value).format("HH:mm");
      val = moment(val, 'HH:mm');
    }
    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: val,
          rules: [
            {
              required: field.required,
              message: messages('common.please.enter')
            }
          ]
        })(
          <TimePicker onChange={this.onChangeTime}
                      format={"HH:mm"}/>
        )}
      </FormItem>
    )
  };
  renderEditingFiled_image = (field) => {
    const {getFieldDecorator} = this.props.form;
    // 上传之后，图片对象直接就绑定到 field.attachmentImages 里面了
    const fileList = field.attachmentImages;
    function handleUploadImageChange(fileList) {
    }

    return (
      <FormItem
        key={field.fieldOID}
        label={field.fieldName}
        colon={true}>
        {getFieldDecorator(field.fieldOID, {
          initialValue: fileList,
          rules: [
            {required: field.required, message: messages('common.please.enter')}
          ]
        })(
          <ImageUpload attachmentType="INVOICE_IMAGES"
                       fileType={["PNG", 'png', 'jpeg', 'jpeg', 'jpg', 'JPG', 'bmp', 'BMP']}
                       defaultFileList={fileList}
                       isShowDefault={true}
                       onChange={handleUploadImageChange}
                       maxNum={field.fieldConstraint ? JSON.parse(field.fieldConstraint).maxNumber : 9}/>
        )}
      </FormItem>
    )
  };
  // -----扩展字段 编辑状态---end
  //渲染性别
  renderGenderOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.value}>{item.messageKey}</Option>
      })
    } else {
      return (<Option value={1} key={1}>
        {messages('enterprise-manage.key244'/*女*/)}
      </Option>)
    }
  };

  //渲染编辑状态
  renderEditing = () => {
    const {getFieldDecorator} = this.props.form;
    const {loading, genderData, personObj} = this.state;
    let fields = personObj.customFormValues ? personObj.customFormValues : [];
    let addFlag = personObj.userOID ? false : true;
    return (
      <div className="info-item-edit-wrap">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key230'/*工号*/)}
                colon={true}>
                {getFieldDecorator('employeeID', {
                  initialValue: personObj.employeeID,
                  rules: [
                    {
                      max: 20,
                      message: messages('enterprise-manage.key278')/*最多输入20个字符*/
                    },
                    {
                      required: true,
                      message: messages("common.please.enter")
                    }
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key231'/*姓名*/)}
                colon={true}>
                {getFieldDecorator('fullName', {
                  initialValue: personObj.fullName,
                  rules: [
                    {
                      max: 40,
                      message: messages('enterprise-manage.key245'/*最多输入40个字符*/)
                    },
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key234'/*邮箱*/)}
                colon={true}>
                {getFieldDecorator('email', {
                  initialValue: personObj.email,
                  rules: [
                    {
                      type: 'email',
                      message: messages('enterprise-manage.key246'/*邮箱格式不对*/)
                    },
                    {
                      required: this.props.tenant.utmSource !== 'wechat',
                      message: messages("common.please.enter"),
                    }
                  ],
                })(
                  <Input placeholder={messages("common.please.enter")}/>)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key235'/*手机*/)}
                colon={true}>
                {getFieldDecorator('mobile', {
                  initialValue: personObj.mobile,
                  rules: [
                    {
                      max: 30,
                      message: messages('enterprise-manage.key247'/*最多输入30个字符*/)
                    },
                    {
                      message: messages('enterprise-manage.key147'/*必须是数字*/),
                      validator: (personObj, value, cb) => {
                        if (value === "" || value === undefined || value === null) {
                          cb();
                          return;
                        }
                        let reg = new RegExp("^[0-9]*$");
                        if (!reg.test(value)) {
                          cb(false);
                        } else {
                          cb();
                        }
                      },
                    }
                  ]
                })(
                  <Input addonBefore={this.props.form.getFieldDecorator('mobilePrefix', {
                    initialValue: personObj.mobileCode,
                  })(
                    BIService.renderMobilePrefix(this.state.preFixList)
                  )}
                         placeholder={messages("common.please.enter")}/>)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key236'/*直属领导*/)}
                colon={true}>
                {getFieldDecorator('directManager', {
                  initialValue: personObj.directManagerName ? [
                    {
                      fullName: personObj.directManagerName,
                      userOID: personObj.directManager
                    }
                  ] : [],
                  rules: []
                })(
                  <Chooser single={true}
                           placeholder={messages("common.please.select")}
                           labelKey="fullName"
                           valueKey="userOID"
                           onChange={this.handleChange}
                           type="user"/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key239'/*人员类型*/)}
                colon={true}>
                {getFieldDecorator('employeeType', {
                  initialValue: personObj.employeeType ? [
                    {
                      value: personObj.employeeTypeCode,
                      messageKey: personObj.employeeType
                    }
                  ] : [],
                  rules: []
                })(
                  <Chooser single={true}
                           type="personTypeModel"
                           labelKey="messageKey"
                           valueKey="value"
                           placeholder={messages("common.please.select")}
                           onChange={this.handleChange}
                           listExtraParams={{systemCustomEnumerationType: "1001"}}/>
                )}
              </FormItem>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key241'/*性别*/)}
                colon={true}>
                {getFieldDecorator('gender', {
                  initialValue: personObj.genderCode,
                  rules: []
                })(
                  <Select
                    className="select-country"
                    showSearch
                    placeholder={messages("common.please.select")}
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  >
                    {this.renderGenderOption(genderData)}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key242'/*生日*/)}
                colon={true}>
                {getFieldDecorator('birthday', {
                  initialValue: personObj.birthday ? moment(personObj.birthday) : "",
                  rules: []
                })(
                  <DatePicker
                    format={'YYYY-MM-DD'}
                    onChange={this.handleChange}/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key243'/*入职时间*/)}
                colon={true}>
                {getFieldDecorator('entryTime', {
                  initialValue: personObj.entryTime ? moment(personObj.entryTime) : "",
                  rules: []
                })(
                  <DatePicker
                    format={'YYYY-MM-DD'}
                    onChange={this.handleChange}/>
                )}
              </FormItem>
            </Col>
          </Row>
          {addFlag ? null :
            <Row gutter={24}>
              <Col span={8}>
                <FormItem
                  label={messages('enterprise-manage.key496'/*公务卡状态*/)}
                  colon={true}>
                  {getFieldDecorator('businessCardStatus', {
                    initialValue: personObj.businessCardStatus,
                    rules: []
                  })(
                    <Select
                      className="select-country"
                      showSearch
                      placeholder={messages("common.please.select")}
                      disabled
                    >
                      <Option value={1} key={1}>{messages('enterprise-manage.key497'/*申请中（政策要求）*/)}</Option>
                      <Option value={2} key={2}>{messages('enterprise-manage.key498'/*申请中（个人要求）*/)}</Option>
                      <Option value={3} key={3}>{messages('enterprise-manage.key499'/*待申请*/)}</Option>
                      <Option value={4} key={4}>{messages('enterprise-manage.key500'/*申请被拒绝*/)}</Option>
                      <Option value={5} key={5}>{messages('enterprise-manage.key501'/*使用中*/)}</Option>
                      <Option value={6} key={6}>{messages('enterprise-manage.key502'/*未开卡*/)}</Option>
                      <Option value={7} key={7}>{messages('enterprise-manage.key503'/*注销*/)}</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
          }

          <div>
            <PositionInfo
              onRef={this.onMountPostionInfo}
              isEdit={true}
              userJobsDTOChange={this.userJobsDTOChange}
              userJobsDTOs={this.state.userJobsDTOs}/>
          </div>

          <div>
            {this.renderExtendTitle()}
          </div>
          <div style={{"width": 500}}>
            {this.renderEditingField(fields)}
          </div>
          <Button type="primary"
                  loading={loading}
                  htmlType="submit">
            {messages("common.save") /*保存*/}
          </Button>
          {personObj.userOID && <Button onClick={this.handleCancel}
                                        style={{marginLeft: 8}}>
            {messages("common.cancel") /*取消*/}
          </Button>}
        </Form>
      </div>
    )
  };

  renderExtendTitle = () => {
    return <p>
      {messages('enterprise-manage.key248'/*个人信息扩展字段*/)}
      &nbsp;&nbsp;<Tooltip title={messages('enterprise-manage.key407')/*员工管理-员工扩展字段里进行编辑*/}>
      <Icon type="question-circle-o"/>
    </Tooltip>
    </p>
  };

  //渲染入口
  renderEnter = () => {
    if (this.props.originEditingStatus) {
      return this.renderEditing();
    } else {
      return this.renderNoEditing();
    }
  };

  render() {
    return (
      <div className="person-basic-info-wrap">
        {this.renderEnter()}
      </div>
    )
  };
}

PersonBasicInfo.propTypes = {
  savedData: React.PropTypes.func.isRequired,//点击保存
  toEditing: React.PropTypes.func.isRequired,//设置编辑
  toNoEditing: React.PropTypes.func.isRequired,//设置显示
  basicInfoData: React.PropTypes.object.isRequired,//基础信息数据对象
  originEditingStatus: React.PropTypes.bool//初始化是否是编辑:默认非编辑
};
PersonBasicInfo.defaultProps = {
  originEditingStatus: false,
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    isOldCompany: state.login.isOldCompany,
  }
}

PersonBasicInfo.contextTypes = {
  router: React.PropTypes.object
};
const WrappedPersonBasicInfo = Form.create()(PersonBasicInfo);
export default connect(mapStateToProps)(WrappedPersonBasicInfo);

